<template>
  <view class="detail-container">
    <!-- 加载状态 -->
    <view v-if="isLoading" class="loading-container">
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 详情内容 -->
    <scroll-view v-else-if="listing" class="detail-scroll" scroll-y>
      <!-- 基本信息卡片 -->
      <view class="info-card">
        <view class="card-header">
          <text class="company-name">{{ listing.company_name }}</text>
          <view class="status-tag" :class="getStatusClass(listing.status)">
            {{ listing.status }}
          </view>
        </view>
        
        <view class="price-section">
          <text v-if="listing.price && listing.price > 0" class="price">¥{{ formatPrice(listing.price) }}</text>
          <text v-else-if="listing.is_negotiable" class="price negotiable">面议</text>
          <text v-else class="price negotiable">面议</text>
        </view>
      </view>

      <!-- 基础信息 -->
      <view class="info-card">
        <view class="card-title">基础信息</view>
        <view class="info-list">
          <view class="info-item">
            <text class="label">信息类型</text>
            <text class="value">{{ listing.listing_type }}</text>
          </view>
          <view class="info-item">
            <text class="label">注册地区</text>
            <text class="value">{{ getLocationText() }}</text>
          </view>
          <view class="info-item">
            <text class="label">成立日期</text>
            <text class="value">{{ formatDate(listing.establishment_date) }}</text>
          </view>
          <view class="info-item">
            <text class="label">注册资本</text>
            <text class="value">{{ listing.registered_capital_range || '未填写' }}</text>
          </view>
          <view class="info-item">
            <text class="label">实缴状态</text>
            <text class="value">{{ listing.paid_in_status || '未填写' }}</text>
          </view>
          <view class="info-item">
            <text class="label">公司类型</text>
            <text class="value">{{ listing.company_type || '未填写' }}</text>
          </view>
        </view>
      </view>

      <!-- 经营状况 -->
      <view class="info-card">
        <view class="card-title">经营状况</view>
        <view class="info-list">
          <view class="info-item">
            <text class="label">税务情况</text>
            <text class="value">{{ listing.tax_status || '未填写' }}</text>
          </view>
          <view class="info-item">
            <text class="label">纳税等级</text>
            <text class="value" :class="getTaxGradeClass(listing.tax_grade)">{{ listing.tax_grade || '未填写' }}</text>
          </view>
          <view class="info-item">
            <text class="label">银行账户</text>
            <text class="value">{{ listing.bank_account_status || '未填写' }}</text>
          </view>
          <view class="info-item">
            <text class="label">银行流水</text>
            <text class="value">{{ listing.bank_flow || '未填写' }}</text>
          </view>
        </view>
      </view>

      <!-- 资产情况 -->
      <view class="info-card">
        <view class="card-title">资产情况</view>
        <view class="asset-grid">
          <view class="asset-item" :class="{ active: listing.has_trademark }">
            <text class="asset-icon">®</text>
            <text class="asset-text">商标</text>
          </view>
          <view class="asset-item" :class="{ active: listing.has_patent }">
            <text class="asset-icon">⚡</text>
            <text class="asset-text">专利</text>
          </view>
          <view class="asset-item" :class="{ active: listing.has_software_copyright }">
            <text class="asset-icon">©</text>
            <text class="asset-text">软著</text>
          </view>
          <view class="asset-item" :class="{ active: listing.has_license_plate }">
            <text class="asset-icon">🚗</text>
            <text class="asset-text">车牌</text>
          </view>
          <view class="asset-item" :class="{ active: listing.has_social_security }">
            <text class="asset-icon">🏥</text>
            <text class="asset-text">社保</text>
          </view>
          <view class="asset-item" :class="{ active: listing.has_bidding_history }">
            <text class="asset-icon">📋</text>
            <text class="asset-text">招投标</text>
          </view>
        </view>
      </view>

      <!-- 详细描述 -->
      <view v-if="listing.description" class="info-card">
        <view class="card-title">详细描述</view>
        <text class="description-text">{{ listing.description }}</text>
      </view>

      <!-- 发布信息 -->
      <view class="info-card">
        <view class="card-title">发布信息</view>
        <view class="info-list">
          <view class="info-item">
            <text class="label">发布者</text>
            <view class="publisher-info">
              <image
                :src="listing.publisher?.avatar_url || '/static/default-avatar.png'"
                class="publisher-avatar"
                mode="aspectFill"
              />
              <text class="value">{{ listing.publisher?.nickname || '匿名用户' }}</text>
              <button
                v-if="listing.publisher && listing.publisher.id && !isOwnListing"
                class="private-chat-btn"
                @click="startPrivateChat"
                :disabled="isStartingChat"
              >
                {{ isStartingChat ? '发起中...' : '私聊' }}
              </button>
            </view>
          </view>
          <!-- 新增手机号显示 -->
          <view class="info-item" v-if="listing.publisher?.phone_number || listing.publisher?.id">
            <text class="label">联系电话</text>

            <!-- 未查看状态: 显示加密手机号 + 查看按钮 -->
            <view v-if="!isContactVisible" class="phone-info">
              <text class="value phone-number encrypted">138****5678</text>
              <button
                class="view-contact-btn"
                @click="viewContact"
                :disabled="viewContactLoading"
              >
                {{ viewContactLoading ? '加载中...' : '查看' }}
              </button>
            </view>

            <!-- 已查看状态: 显示真实手机号 + 拨打按钮 -->
            <view v-else class="phone-info">
              <text class="value phone-number">{{ realContactInfo?.phone_number || listing.publisher.phone_number }}</text>
              <button class="call-btn" @click="makePhoneCall">
                拨打电话
              </button>
            </view>
          </view>
          <view class="info-item">
            <text class="label">发布时间</text>
            <text class="value">{{ formatDateTime(listing.created_at) }}</text>
          </view>
          <view v-if="listing.expires_at" class="info-item">
            <text class="label">有效期至</text>
            <text class="value">{{ formatDateTime(listing.expires_at) }}</text>
          </view>
        </view>
      </view>
    </scroll-view>
    
    <!-- 错误状态 -->
    <view v-else class="error-container">
      <text class="error-text">信息不存在或已被删除</text>
      <button class="back-btn" @click="goBack">返回</button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { listingAPI, chatAPI, utils, contactViewAPI } from '@/utils/api.js'
import CreditChecker from '@/utils/creditChecker.js'

// 响应式数据
const listing = ref(null)
const isLoading = ref(true)
const isStartingChat = ref(false)
const isContactVisible = ref(false)       // 联系方式是否已查看
const viewContactLoading = ref(false)     // 查看联系方式加载状态
const realContactInfo = ref(null)         // 真实的联系方式数据

// 计算属性
const isOwnListing = computed(() => {
  if (!listing.value || !listing.value.publisher) return false
  const currentUser = utils.getCurrentUser()
  return currentUser && currentUser.id === listing.value.publisher.id
})

// 生命周期
onLoad((options) => {
  const { id } = options
  if (id) {
    loadDetail(id)
  } else {
    isLoading.value = false
  }
})

// 方法定义
const loadDetail = async (id) => {
  try {
    isLoading.value = true
    
    const response = await listingAPI.getListingDetail(id)
    
    if (response.success) {
      listing.value = response.data
    } else {
      utils.handleError(new Error(response.message), '获取详情失败')
    }
    
  } catch (error) {
    utils.handleError(error, '获取详情失败')
  } finally {
    isLoading.value = false
  }
}

const goBack = () => {
  uni.navigateBack()
}

/**
 * 查看联系方式(需要消耗额度)
 */
const viewContact = async () => {
  if (!listing.value?.publisher?.id) {
    uni.showToast({
      title: '发布者信息不完整',
      icon: 'none'
    })
    return
  }

  try {
    viewContactLoading.value = true

    // 1. 先检查配置
    const configResponse = await contactViewAPI.getConfig()
    const enableFee = configResponse.success && configResponse.data.enable_contact_view_fee === '1'

    if (!enableFee) {
      // 配置禁用收费,直接显示已有的联系方式,不调用后端接口
      console.log('配置禁用收费,直接显示联系方式')
      realContactInfo.value = {
        phone_number: listing.value.publisher.phone_number,
        wechat_id: listing.value.publisher.wechat_id
      }
      isContactVisible.value = true
      uni.showToast({
        title: '获取成功',
        icon: 'success'
      })
      return
    }

    // 2. 配置启用收费,检查额度
    const hasCredit = await CreditChecker.checkContactViewCredit({
      fromPage: `/pages/listings/detail?id=${listing.value.id}`
    })

    if (!hasCredit) {
      return // 额度不足时,CreditChecker会自动弹窗引导购买
    }

    // 3. 调用现有的contact-view接口获取真实联系方式
    const response = await contactViewAPI.getUserContact(listing.value.publisher.id)

    if (response.success) {
      // 4. 保存真实联系方式并显示
      realContactInfo.value = response.data
      isContactVisible.value = true

      // 5. 如果使用了购买的额度,本地扣减
      if (response.data.used_credits) {
        CreditChecker.reduceLocalCredit(CreditChecker.CREDIT_TYPES.CONTACT_VIEW, 1)
      }

      uni.showToast({
        title: '获取成功',
        icon: 'success'
      })
    } else {
      uni.showToast({
        title: response.message || '获取失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('查看联系方式失败:', error)
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
  } finally {
    viewContactLoading.value = false
  }
}

// 拨打电话(修改为使用realContactInfo)
const makePhoneCall = () => {
  const phoneNumber = realContactInfo.value?.phone_number || listing.value?.publisher?.phone_number
  if (phoneNumber) {
    uni.makePhoneCall({
      phoneNumber: phoneNumber,
      fail: (err) => {
        console.error('拨打电话失败:', err)
        uni.showToast({
          title: '拨打电话失败',
          icon: 'error'
        })
      }
    })
  }
}

// 发起私聊
const startPrivateChat = async () => {
  if (!listing.value?.publisher?.id) {
    uni.showToast({
      title: '发布者信息不完整',
      icon: 'none'
    })
    return
  }

  try {
    isStartingChat.value = true

    // 发起私聊
    const response = await chatAPI.startPrivateChat(listing.value.publisher.id)

    if (response.success) {
      // 跳转到私聊页面
      uni.navigateTo({
        url: `/pages/chat/private?userId=${listing.value.publisher.id}&nickname=${encodeURIComponent(listing.value.publisher.nickname || '用户')}`
      })
    } else {
      uni.showToast({
        title: response.message || '发起私聊失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('发起私聊错误:', error)
    uni.showToast({
      title: '发起私聊失败',
      icon: 'none'
    })
  } finally {
    isStartingChat.value = false
  }
}

// 工具方法
const getStatusClass = (status) => {
  const classMap = {
    '在售': 'status-selling',
    '已售': 'status-sold',
    '下架': 'status-offline'
  }
  return classMap[status] || 'status-default'
}

const getLocationText = () => {
  const province = listing.value?.registration_province || ''
  const city = listing.value?.registration_city || ''

  if (!province && !city) {
    return '未填写'
  }

  if (province && city) {
    // 如果省份和城市相同（如北京市、上海市等直辖市），只显示一个
    if (province === city || city.includes(province.replace('市', '').replace('省', '').replace('自治区', ''))) {
      return province
    }
    return `${province} ${city}`
  }

  return province || city
}

const formatDate = (dateStr) => {
  if (!dateStr) return '未填写'
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return `${year}年${month}月${day}日`
}

const formatDateTime = (timeStr) => {
  if (!timeStr) return '未填写'
  const date = new Date(timeStr)
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return `${year}年${month}月${day}日`
}

const formatPrice = (price) => {
  if (!price) return '0'
  return Number(price).toLocaleString('zh-CN')
}

const getTaxGradeClass = (grade) => {
  if (!grade || grade === '未填写' || grade === '未开通') {
    return 'tax-grade-default'
  }
  
  const gradeClassMap = {
    'A': 'tax-grade-a',
    'B': 'tax-grade-b', 
    'M': 'tax-grade-m',
    'C': 'tax-grade-c',
    'D': 'tax-grade-d'
  }
  
  return gradeClassMap[grade] || 'tax-grade-default'
}
</script>

<style scoped>
.detail-container {
  height: 100vh;
  background-color: #f5f5f5;
}

.loading-container,
.error-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.loading-text,
.error-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 40rpx;
}

.back-btn {
  padding: 20rpx 40rpx;
  background: #22c55e;
  color: white;
  border: none;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.detail-scroll {
  height: 100vh;
  padding: 20rpx;
}

.info-card {
  background: white;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.company-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
}

.status-tag {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 22rpx;
  color: white;
}

.status-selling {
  background: #22c55e;
}

.status-sold {
  background: #ef4444;
}

.status-offline {
  background: #6b7280;
}

.price-section {
  text-align: center;
  padding: 20rpx 0;
}

.price {
  font-size: 48rpx;
  font-weight: bold;
  color: #ef4444;
}

.price.negotiable {
  color: #f59e0b;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
  padding-bottom: 15rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.info-list {
  display: flex;
  flex-direction: column;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.info-item:last-child {
  border-bottom: none;
}

.publisher-info {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.publisher-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 30rpx;
  flex-shrink: 0;
  background-color: #f0f0f0;
}

.private-chat-btn {
  background: #007aff;
  color: white;
  border: none;
  border-radius: 20rpx;
  padding: 8rpx 16rpx;
  font-size: 24rpx;
  min-width: 80rpx;
  height: 56rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.private-chat-btn:disabled {
  background: #ccc;
  color: #999;
}

.phone-info {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.phone-number {
  color: #22c55e;
  font-weight: 600;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}

.phone-number.encrypted {
  color: #999;
  font-style: italic;
}

.view-contact-btn {
  background: #22c55e;
  color: white;
  border: none;
  border-radius: 20rpx;
  padding: 8rpx 20rpx;
  font-size: 24rpx;
  min-width: 80rpx;
  height: 56rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.view-contact-btn[disabled] {
  background: #ccc;
  color: #999;
}

.call-btn {
  background: #22c55e;
  color: white;
  border: none;
  border-radius: 20rpx;
  padding: 8rpx 16rpx;
  font-size: 24rpx;
  min-width: 80rpx;
  height: 56rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.call-btn:active {
  background: #16a34a;
}

.label {
  font-size: 28rpx;
  color: #666;
  width: 160rpx;
}

.value {
  font-size: 28rpx;
  color: #333;
  flex: 1;
  text-align: right;
}

.asset-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
}

.asset-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30rpx 20rpx;
  border: 2rpx solid #e5e5e5;
  border-radius: 12rpx;
  background: #f9f9f9;
}

.asset-item.active {
  border-color: #22c55e;
  background: #f0f9ff;
}

.asset-icon {
  font-size: 40rpx;
  margin-bottom: 10rpx;
}

.asset-text {
  font-size: 24rpx;
  color: #666;
}

.asset-item.active .asset-text {
  color: #22c55e;
  font-weight: bold;
}

.description-text {
  font-size: 28rpx;
  color: #333;
  line-height: 1.6;
}

/* 纳税等级样式 */
.tax-grade-a {
  color: #10b981;
  font-weight: bold;
}

.tax-grade-b {
  color: #22c55e;
  font-weight: bold;
}

.tax-grade-m {
  color: #3b82f6;
  font-weight: bold;
}

.tax-grade-c {
  color: #f59e0b;
  font-weight: bold;
}

.tax-grade-d {
  color: #ef4444;
  font-weight: bold;
}

.tax-grade-default {
  color: #9ca3af;
}
</style>
